﻿/*
* ========================================================================
* 类说明：
*   
* 
* 作者：HGS   时间：2024/9/4 19:52:19
* 
* 修改者：         时间：           
* 修改说明：
* ========================================================================
*/

using HslCommunication.ModBus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PopupWinTool.Common
{
    public class ModbusTcpUnityHSL
    {
        private ModbusTcpNet modbusTcpNet;
        /// <summary>
        /// Modbus客户端声明
        /// </summary>
        public ModbusTcpNet ModbusTcpNet
        {
            get { return modbusTcpNet; }
            set { modbusTcpNet = value; }
        }

        /// <summary>
        /// IP地址
        /// </summary>
        private string IP;
        /// <summary>
        /// 端口号
        /// </summary>
        private int Port;
        /// <summary>
        /// 连接状态
        /// </summary>
        public bool ConnOK { get; set; }

        /// <summary>
        /// HSL-ModbusTcp操作帮助类
        /// </summary>
        public ModbusTcpUnityHSL(string IP, int Port)
        {
            //modbusTcpNet = new ModbusTcpNet(IP, Port, 1);  //后面的1表示站号（无需写入，写入0后读取数据会失败；写入1后一切都正常）
            modbusTcpNet = new ModbusTcpNet(IP, Port, 1);
            modbusTcpNet.ReceiveTimeOut = 1000;
        }
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            try
            {
                if (modbusTcpNet == null)
                    return false;

                var connServer = modbusTcpNet.ConnectServer();
                ConnOK = connServer.IsSuccess;
                return ConnOK;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[ModbusTcpUnityHSL.Connect]异常，{ex.Message}，{ex.StackTrace}");
                ConnOK = false;
            }
            return false;
        }
        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            try
            {
                if (modbusTcpNet == null)
                    return true;

                modbusTcpNet.ConnectClose();
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[ModbusTcpUnityHSL.Close]异常，{ex.Message}，{ex.StackTrace}");
            }
            return true;
        }
    }
}
